<?php

namespace App\Http\Services;

use App\Http\Dao\MemoDao;
use App\Http\Dao\RemindDao;
use App\Models\MemoModel;
use Exception;
use Illuminate\Support\Facades\DB;

/**
 * @property MemoDao $memoDao
 */
class MemoService
{

    public function __construct(MemoDao $memoDao)
    {
        $this->memoDao = $memoDao;
    }

    public function addMemo($post)
    {
        return $this->memoDao->add($post);
    }

    public function updateMemo($post)
    {
        try {
            Db::transaction(function () use ($post) {
                $memosId = $this->memoDao->editOne($post);
                if (!$memosId) {
                    throw new Exception('修改失败');
                }

                $addRemind = [
                    'memos_id' => $post['id'],
                    'user_id' => request()->userInfo['id'],
                    'sent_time' => $post['reminder_time'] ?? "",
                ];
                $result = (new RemindDao())->add($addRemind);
                if (!$result) {
                    throw new Exception('添加失败');
                }
            });
            return true;
        } catch (Exception $e) {
            return false;
        }
    }

    public function getList($post)
    {
        $query = MemoModel::query();
        $query->where('user_id', request()->userInfo['id']);
        if (!empty($post['search_values']) && $post['search_values'] != 'undefined') {
            $query->where(function ($query) use ($post) {
                $query->where('title', 'like', '%' . $post['search_values'] . '%')
                    ->orWhere('desc', 'like', '%' . $post['search_values'] . '%');
            });
        }

        return $query->orderBy('priority', 'desc')->orderBy($post['sort'], $post['by'])->paginate($post['page_size'])->toArray();
    }

    public function getDetail($id)
    {
        $where = [
            ['id', '=', $id],
            ['user_id', '=', request()->userInfo['id']]
        ];
        $info = $this->memoDao->getOne($where);
        return $info ? $info->toArray() : [];
    }

    public function deleteMemo($id)
    {
        return $this->memoDao->deleteOne($id);
    }

    public function topMemo($post)
    {
        return $this->memoDao->editOne(['id' => $post['id'], 'priority' => $post['priority']]);
    }

    public function doneMemo($post)
    {
        return $this->memoDao->editOne(['id' => $post['id'], 'status' => $post['status']]);
    }
}
